const Base = require('./base.js');
const Config = require('./gameidleshopconfig.js');

const log4js = require('log4js')
const logger = log4js.getLogger()
var sd = require('silly-datetime');

const limitminutes=2



module.exports = class extends Base {

  limit(time){
    const cur_time=this.getTime()
    return cur_time-time>limitminutes*60
  }


  //有推荐码为，注册，没有则是普通登陆
  async loginAction() {
    const wallet_address = this.post('wallet_address');
    const user = await this.model('gameuser')
      .where({ wallet_address: wallet_address})
      .find();

    if (!think.isEmpty(user)) {
      if(!this.limit(user.last_login_time)){
        return this.fail(8021,{zh:`操作频繁,请${limitminutes}分钟后再试。`,en:`frequent operation , please try ${limitminutes} minuts later`})
      }
      if(user.isBan=="1"||user.isBan==1){
        console.log(`${wallet_address}:isBan`)
        return this.fail(8140, "该账号已被限制");
      }
    }

    const today= (new Date(new Date().toLocaleDateString()).getTime())/1000;

    var IP =(this.ctx.state.rip);
    if(this.ctx.state.rip == "")
    {
      IP = this.ctx.ip;
    }
    console.log("1"+this.ctx.state.rip+"1");
    console.log(this.ctx.ip);
    console.log(IP);
    //限制IP登录
    if (!think.isEmpty(user)) {

      console.log("进入ip限制");


      const IPs=await this.model('gameuser').query(`SELECT wallet_address FROM nideshop_gameuser WHERE last_login_ip='${IP}' AND last_login_time>=${today}`)



      var isexist = JSON.stringify(IPs).indexOf(wallet_address);

      logger.info("["+sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss') +"]"+wallet_address+":"+IP+ "       "+(isexist<0));

      if (isexist<0 && IPs.length > 2) {
        return this.fail(8020, "IP重复");
      }

      if(user.isBan=="1"||user.isBan==1){
        return this.fail(8140, "该账号已被限制");
      }
    }

    let userInfo ={
      id:"",
      wallet_address: wallet_address,
      username: wallet_address,
      register_time: parseInt(Date.now() / 1000),
      password_salt: "",
      lead_InvitationCode: "",
      last_login_time: parseInt(Date.now() / 1000),
      m_InvitationCode: "",
      hashrate: 0,
      underling_hashrate: 0,
      last_login_ip: IP,
      day_activate: 0,
      gems: 0,
      automatic_bonus_time: 0,
      underling_limit: 7,
      day_automatic_bonus_time: 0,
      begin_automatic_bonus_time: 0,
      underling_count: 0,
      level: 1,
      cur_hashrate: 0,
      totalhashrate: 0,
      record: "",
      limit_add_money: 0,
      day_add_money: 0,
      SAT: 0,
      SATrecord: "",
      isBan: 0,
    }

    if (this.post('lead_InvitationCode')) {

      const lead_InvitationCode = this.post('lead_InvitationCode');
      const lead = await this.model('gameuser')
        .where({ m_InvitationCode: lead_InvitationCode })
        .find();
      if(!think.isEmpty(user)){
        return this.fail(8021, {zh:"该地址已激活,请重新登录",en:'wallet_address already activte,please login again'});
      }
      if (think.isEmpty(lead)) {
        return this.fail(8000, '邀请码无效');
      };

      if (lead.underling_count >= lead.underling_limit) {
        return this.fail(8001, '该邀请码人数到达上限，请更换邀请码或者请邀请人升级');
      };        

      if (lead.isBan=="1"||lead.isBan==1) {
        return this.fail(8141, '该邀请码已被限制');
      };

      //注册新邀请的账号
      if (think.isEmpty(user) && lead.underling_count < lead.underling_limit) {
        userInfo.lead_InvitationCode=lead_InvitationCode;
        userInfo.m_password_salt= Math.random()
          .toString(36)
          .slice(-8);
          
        const gameConfig = await this.model('gameconfig')
          .where({ gamename: "idleshop" })
          .select();

        if (gameConfig && gameConfig.length > 0) {
          let t_InviteCode = gameConfig[0].maxInviteCode + 1;
          userInfo.m_InvitationCode = t_InviteCode.toString(36) + (Math.random().toString(36).slice(-2));
          await this.model('gameconfig')
            .where({ gamename: "idleshop" })
            .update({
              maxInviteCode: t_InviteCode
            });
        } else {
          return this.fail(8010, "游戏配置名称错误");
        }        

        userInfo.id=await this.model('gameuser').add(userInfo);
        
        await this.model('gameuser')
          .where({ m_InvitationCode: lead_InvitationCode })
          .increment(
            "underling_count", 1
          );
      }
    } else if (think.isEmpty(user)) {
      return this.fail(8002, '钱包地址未激活，请输入邀请码激活');
    }
    console.log("user="+JSON.stringify(user));


    if(JSON.stringify(user)!="{}"){
      //console.log("进来了呀")
      userInfo=user;
    }

    if (userInfo.day_activate == 0) {
      await this.model('gameuser_realTime_statistics')
        .where({
          date: (new Date(new Date().toLocaleDateString()).getTime()) / 1000
        })
        .increment(
          "DAU_realTime", 1
        );
    }

    // 更新登录信息
    console.log("更新信息")
    await this.model('gameuser')
      .where({ wallet_address: wallet_address })
      .update({
        last_login_ip: IP,
        day_activate: 1
      });
      
    const TokenSerivce = this.service('token', 'gameuser');
    const sessionKey = await TokenSerivce.create({
      user_id: userInfo.id
    });

    if (think.isEmpty(sessionKey)) {
      return this.fail(8003, '登录失败');
    }
    // console.log("userInfo.level="+userInfo.level);
    const levelInfo = Config.levelJson[userInfo.level - 1];
    // console.log("levelInfo="+levelInfo);
    // console.log("levelInfo.level="+levelInfo.level);

    return this.success({
      token: sessionKey,
      userInfo: userInfo,
      levelInfo:levelInfo,
      Current_server_time: parseInt(Date.now() / 1000)
    });
  }
  
  async logoutAction() {
    if (this.ctx.header['x-nideshop-token']) {
      this.ctx.header['x-nideshop-token'] = '';
    }
    return this.success('退出登录');
  }
};
